package com.quanyan.stadium.service.admin.impl;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.RespClubPlainInfo;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.vo.Image;
import com.quanyan.place.entity.apiresp.RespCity;
import com.quanyan.stadium.api.req.ReqAuthorizeClub;
import com.quanyan.stadium.api.req.ReqId;
import com.quanyan.stadium.api.req.ReqIdAndPage;
import com.quanyan.stadium.api.req.admin.*;
import com.quanyan.stadium.api.resp.admin.*;
import com.quanyan.stadium.biz.BizGameSystemDao;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.*;
import com.quanyan.stadium.entity.vo.GameEvent;
import com.quanyan.stadium.entity.vo.MultiMedia;
import com.quanyan.stadium.entity.vo.PlaceInfo;
import com.quanyan.stadium.enums.ErrorEnum;
import com.quanyan.stadium.enums.GameSystemConfigEnum;
import com.quanyan.stadium.enums.GameTypeConfigEnum;
import com.quanyan.stadium.mapper.*;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.stadium.service.gameSign.GameSignUpService;
import com.quanyan.stadium.service.commonComponent.OfficialGameCache;
import com.quanyan.stadium.service.admin.AdminGameEventService;
import com.quanyan.stadium.utils.GameUtils;
import com.quanyan.user.response.RespUserInfoBase;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @author xiaoxiao
 * @date 16/4/11-14:42
 */

@Service("adminGameEventService")
public class AdminGameEventServiceImpl implements AdminGameEventService {

    private final static Logger logger = LoggerFactory.getLogger(AdminGameEventServiceImpl.class);

    @Autowired
    private BizGameSystemDao bizGameSystemDao;

    @Autowired
    private TbGameClubOfficialMapper tbGameOfficialClubMapper;

    @Autowired
    private TbGameEventMapper tbGameEventMapper;

    @Autowired
    private BaseService baseService;

    @Autowired
    private OfficialGameCache officialGameCache;

    @Autowired
    private TbGameOrderMapper orderMapper;

    @Autowired
    private TbGameEventMapper gameEventMapper;

    @Autowired
    private GameSignUpService gameSignUpService;

    @Autowired
    private TbGameBannerMapper tbGameBannerMapper;

    @Autowired
    private TbGameCommonParameterMapper tbGameCommonParameterMapper;

    @Value("${stadium.refund.url}")
    private String refundUrl;

    @Override
    public boolean updateGameEventStatus(ReqGameEventStatusUpdate reqGameEventStatusUpdate) {
        TbGameEvent cur = bizGameSystemDao.selectTbGameEvent(reqGameEventStatusUpdate.getGameEventId());
        if (cur.getEndTime().after(new Date())) {
            return false;
        }
        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setId(reqGameEventStatusUpdate.getGameEventId());
        tbGameEvent.setIsDelete(reqGameEventStatusUpdate.getIsCancel());
        int n = tbGameEventMapper.updateByPrimaryKeySelective(tbGameEvent);
        if (n>0) {
            if (reqGameEventStatusUpdate.getIsCancel().intValue() == GameConstants.IS_DELETE.intValue()) {
                try{
                    gameSignUpService.refound(reqGameEventStatusUpdate.getGameEventId());
                }catch (Exception e)  {
                    logger.error("赛事退款失败, 当前赛事ID:{}", reqGameEventStatusUpdate.getGameEventId());
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public RespGameEventDetail queryTbGameEventList(ReqSearchGameEvent reqSearchGameEvent) {
        RespGameEventDetail result = new RespGameEventDetail();
        TbGameEventExample example = new TbGameEventExample();
        TbGameEventExample.Criteria criteria = example.createCriteria();
        criteria.andGameEventTypeEqualTo(reqSearchGameEvent.getGameType());
        criteria.andCategoryIdEqualTo(reqSearchGameEvent.getCategoryId());
        if (null!=reqSearchGameEvent.getCityId() && reqSearchGameEvent.getCityId()>0) {
            criteria.andCityIdEqualTo(reqSearchGameEvent.getCityId());
        }
        if (null!=reqSearchGameEvent.getDistrictId() && reqSearchGameEvent.getDistrictId()>0) {
            criteria.andDistrictIdEqualTo(reqSearchGameEvent.getDistrictId());
        }
        if (null!=reqSearchGameEvent.getPlaceId() && reqSearchGameEvent.getPlaceId()>0) {
            criteria.andPlaceIdEqualTo(reqSearchGameEvent.getPlaceId());
        }
        if (null!=reqSearchGameEvent.getGameCode() && reqSearchGameEvent.getGameCode().trim().length()>0) {
            criteria.andGameNumberLike("%"+reqSearchGameEvent.getGameCode()+"%");
        }
        if (null!=reqSearchGameEvent.getCreateTime() && reqSearchGameEvent.getCreateTime()>0) {
            criteria.andCreateTimeBetween(DateUtils.dayBegin(new Date(reqSearchGameEvent.getCreateTime())), DateUtils.dayEnd(new Date(reqSearchGameEvent.getCreateTime())));
        }
        if (null!=reqSearchGameEvent.getStartTime() && reqSearchGameEvent.getStartTime()>0) {
            criteria.andStartTimeBetween(DateUtils.dayBegin(new Date(reqSearchGameEvent.getStartTime())), DateUtils.dayEnd(new Date(reqSearchGameEvent.getStartTime())));
        }
        int total = tbGameEventMapper.countByExample(example);
        if (total > 0) {
            example.setOrderByClause("update_time desc");
            List<TbGameEvent> temp  = tbGameEventMapper.selectByExample(example);
            Set<Integer> placeIds = new HashSet<>();
            for (TbGameEvent tbGameEvent : temp) {
                placeIds.add(tbGameEvent.getPlaceId());
            }
            result.setPlaceInfoMap(baseService.queryPlaceInfoMsgList(new ArrayList<Integer>(placeIds)));
            result.setPageObj(PageObj.create(total, reqSearchGameEvent.getPageNo(), reqSearchGameEvent.getPageSize(), temp));
        }
        return result;
    }

    @Override
    public List<TbGameEvent> queryOfficialGameEventByPlaceIdAndCategoryId(ReqOfficialGameEvent reqOfficialGameEvent) {
        TbGameEventExample example = new TbGameEventExample();
        TbGameEventExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(reqOfficialGameEvent.getCategoryId());
        if (null!=reqOfficialGameEvent.getCityId()) {
            criteria.andCityIdEqualTo(reqOfficialGameEvent.getCityId());
        }
        if (null!=reqOfficialGameEvent.getDistrictId()) {
            criteria.andDistrictIdEqualTo(reqOfficialGameEvent.getDistrictId());
        }
        if (null!=reqOfficialGameEvent.getPlaceId()) {
            criteria.andPlaceIdEqualTo(reqOfficialGameEvent.getPlaceId());
        }
        if (null!=reqOfficialGameEvent.getGameMonth()) {
            criteria.andGameMonthEqualTo(reqOfficialGameEvent.getGameMonth());
        }
        if (null == reqOfficialGameEvent.getGameType()) {
            criteria.andGameEventTypeEqualTo((byte) GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_PLACE.getId());
        }else {
            criteria.andGameEventTypeEqualTo(reqOfficialGameEvent.getGameType());
        }
        List<TbGameEvent> tbGameEvents = tbGameEventMapper.selectByExample(example);
        if (null!=tbGameEvents && tbGameEvents.size()>0) {
            return tbGameEvents;
        }
        return null;
    }

    @Override
    public APIResponse<GameEvent> createGameEvent(ReqCreateGameEventExtraMsg createGameEvent) throws InvocationTargetException, IllegalAccessException {
        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setType(GameConstants.OFFICIAL_CREATE);
        tbGameEvent.setPrice(createGameEvent.getPrice());
        tbGameEvent.setStartTime(new Date(createGameEvent.getStartTime()));
        tbGameEvent.setEndTime(new Date(createGameEvent.getEndTime()));
        tbGameEvent.setSignStartTime(new Date(createGameEvent.getSignStartTime()));
        tbGameEvent.setSignEndTime(new Date(createGameEvent.getSignEndTime()));
        tbGameEvent.setCategoryId(createGameEvent.getCategoryId());
        tbGameEvent.setPlaceId(createGameEvent.getPlaceInfo().getPlaceId());
        tbGameEvent.setCityId(createGameEvent.getPlaceInfo().getCityId());
        tbGameEvent.setDistrictId(createGameEvent.getPlaceInfo().getDistrictId());
        tbGameEvent.setGameSystemType(createGameEvent.getGameSystemType());
        tbGameEvent.setGameEventType(createGameEvent.getGameEventType());
        if (null!=createGameEvent.getGameGradeLevel()) {
            tbGameEvent.setGameGradeLevelType(createGameEvent.getGameGradeLevel());
        }
        if (createGameEvent.getCategoryId().intValue() == GameConstants.CATEGORY_ID_FOOTBALL ||
                createGameEvent.getCategoryId().intValue() == GameConstants.CATEGORY_ID_BASKETBALL) {
            tbGameEvent.setGameTeamType(GameConstants.IS_DELETE);
        }
        if (null != createGameEvent.getGameCategoryType()) {
            tbGameEvent.setGameCategoryType(createGameEvent.getGameCategoryType());
        }else {
            if (createGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId() ||
                    createGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_PK.getId()) {
            }else {
            }
        }
        tbGameEvent.setIsVisible(GameConstants.IS_DELETE);
        tbGameEvent.setPayType(createGameEvent.getPayType());

        tbGameEvent.setPayContactMobile(createGameEvent.getHostMobile());
        tbGameEvent.setManagerMobile(createGameEvent.getHostMobile());
        String gameCode = GameUtils.generateGameCode(createGameEvent.getGameEventType(), createGameEvent.getCategoryId(), createGameEvent.getPlaceInfo().getPlaceId(), createGameEvent.getGameSystemType().byteValue());
        tbGameEvent.setGameNumber(gameCode);
        if (createGameEvent.getTeamLimitNum() == 0) {
            tbGameEvent.setTeamLimitNum(Integer.MAX_VALUE);
            tbGameEvent.setInventoryLevel(Integer.MAX_VALUE);
        }else {
            tbGameEvent.setTeamLimitNum(createGameEvent.getTeamLimitNum());
            tbGameEvent.setInventoryLevel(createGameEvent.getTeamLimitNum());
        }
        tbGameEvent.setGameDesc(createGameEvent.getBodyDesc());
        Gson gson = new Gson();
        MultiMedia multiMedia = new MultiMedia();
        Image image = new Image();
        multiMedia.setType(GameConstants.IS_NOT_DELETE);   //图片
        TbGameCommonParameter name = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                GameConstants.BASE_CONFIG_KEY_OFFICIAL_HOST_NAME);
        TbGameCommonParameter icon = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                GameConstants.BASE_CONFIG_KEY_OFFICIAL_HOST_ICON);
        if (createGameEvent.getGameEventType().intValue() == GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId()) {  //积分赛
            image.setImageUrl(icon.getParameterValue());
        }else {
            image = createGameEvent.getImage();
        }
        tbGameEvent.setManagerName(name.getParameterValue()+gameCode);
        multiMedia.setImage(image);
        tbGameEvent.setMultiMedia(gson.toJson(multiMedia));

        if (createGameEvent.getGameEventType().intValue() != GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId()) {
            if (StringUtils.isEmpty(createGameEvent.getName()) && createGameEvent.getGameEventType().intValue() == GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_PLACE.getId()) {
                tbGameEvent.setName(createGameEvent.getPlaceInfo().getName() + createGameEvent.getGameMonth() +"月场馆赛(决赛)");
            }else {
                tbGameEvent.setName(createGameEvent.getName());
            }
            if (this.validateGameEventExist(createGameEvent.getPlaceInfo().getPlaceId(), createGameEvent.getGameMonth(), createGameEvent.getCategoryId())) {
                return APIResponse.returnFail("赛事已经创建,无法重新创建");
            }
            tbGameEvent.setGameMonth(createGameEvent.getGameMonth());
            tbGameEvent.setComplementeTime(new Date(createGameEvent.getComplementeTime()));
        }else {
            TbGameEvent parentGameEvent = bizGameSystemDao.selectTbGameEvent(createGameEvent.getParentId());
            tbGameEvent.setParentId(parentGameEvent.getId());
            tbGameEvent.setName(parentGameEvent.getName().replaceAll("决赛", "排位"));
        }

        tbGameEvent = bizGameSystemDao.insertTbGameEvent(tbGameEvent);
        if (null == tbGameEvent.getId()) {
            //回滚activityId状态
            return APIResponse.returnFail(ErrorEnum.ERROR_DB.getId(), ErrorEnum.ERROR_DB.getLabel());
        }

        officialGameCache.getGameEvent(tbGameEvent.getId());
        logger.info("官方创建赛事成功,开始缓存赛事信息,赛事ID{}", tbGameEvent.getId());
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse authorizeClub(ReqAuthorizeClub reqAuthorizeClub) {
        /*if (reqAuthorizeClub.getSignExpireTime() <= reqAuthorizeClub.getSignStartTime()) {
            return APIResponse.returnFail("授权结束时间不能小于等于开始时间");
        }
        if (reqAuthorizeClub.getSignStartTime()<new Date().getTime()) {
            return APIResponse.returnFail("授权开始时间不能小于当前时间");
        }
        TbGameClubOfficialExample example = new TbGameClubOfficialExample();
        TbGameClubOfficialExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(reqAuthorizeClub.getClubId());
        criteria.andPlaceIdEqualTo(reqAuthorizeClub.getPlaceId());
        criteria.andSignExpireTimeGreaterThan(new Date());
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        List<TbGameClubOfficial> gameClubOfficials = tbGameOfficialClubMapper.selectByExample(example);
        if (null!=gameClubOfficials && gameClubOfficials.size()>0) {
            for (TbGameClubOfficial tbGameClubOfficial: gameClubOfficials) {
                if ((tbGameClubOfficial.getSignStartTime().getTime()>reqAuthorizeClub.getSignStartTime() && tbGameClubOfficial.getSignStartTime().getTime()<reqAuthorizeClub.getSignExpireTime()) ||
                        (tbGameClubOfficial.getSignStartTime().getTime()<reqAuthorizeClub.getSignStartTime() && tbGameClubOfficial.getSignExpireTime().getTime()>reqAuthorizeClub.getSignExpireTime()) ||
                        (tbGameClubOfficial.getSignExpireTime().getTime()>reqAuthorizeClub.getSignStartTime() && tbGameClubOfficial.getSignExpireTime().getTime()<reqAuthorizeClub.getSignExpireTime())) {
                    return APIResponse.returnFail("授权时间段已存在,请重新设置");
                }
            }
        }

        TbGameClubOfficial record = new TbGameClubOfficial();
        record.setClubId(reqAuthorizeClub.getClubId());
        record.setCityId(reqAuthorizeClub.getCityId());
        record.setDistrictId(reqAuthorizeClub.getDistrictId());
        record.setPlaceId(reqAuthorizeClub.getPlaceId());
        record.setCategoryId(reqAuthorizeClub.getCategoryId());
        record.setSignStartTime(new Date(reqAuthorizeClub.getSignStartTime()));
        record.setSignExpireTime(new Date(reqAuthorizeClub.getSignExpireTime()));*/
        TbGameClubOfficial record = new TbGameClubOfficial();
        record.setClubId(reqAuthorizeClub.getClubId());
        if (tbGameOfficialClubMapper.insertSelective(record)>0) {
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("授权失败");
    }

    @Override
    public APIResponse closeClubAuthorize(Integer clubAuthorizeId) {
        TbGameClubOfficial record = new TbGameClubOfficial();
        record.setId(clubAuthorizeId);
        record.setIsDelete(GameConstants.IS_DELETE);
        if (tbGameOfficialClubMapper.updateByPrimaryKeySelective(record)>0) {
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("授权失败");
    }

    @Override
    public APIResponse<PageObj<List<RespOrderList>>> queryOrderList(ReqOrderList request) {
        TbGameOrderExample example = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = example.createCriteria();
        PageObj<List<RespOrderList>> page = new PageObj<List<RespOrderList>>();
        if(!StringUtils.isBlank(request.getOrderNO())){
            criteria.andTradeOrderNoEqualTo(request.getOrderNO());
        }
        if(!StringUtils.isBlank(request.getGameName())){
            criteria.andGameNameLike(request.getGameName());
        }
        if(!StringUtils.isBlank(request.getGameId())){
            criteria.andGameEventIdEqualTo(Integer.parseInt(request.getGameId()));
        }
        if(!StringUtils.isBlank(request.getOrderType())){
            criteria.andOrderStatusEqualTo(Byte.parseByte(request.getOrderType()));
        }
        if(!StringUtils.isBlank(request.getContract())){
            criteria.andContactLike(request.getContract());
        }
        if(!StringUtils.isBlank(request.getContractMobile())){
            criteria.andContractMobileLike(request.getContractMobile());
        }

        Integer totalCount = orderMapper.countByExample(example);
        example.setPage(new Page((request.getPageNum() ) * request.getPageSize(), request.getPageSize(), totalCount));
        List<TbGameOrder> list = orderMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            return APIResponse.returnSuccess(page);
        }
        PageObj<List<TbGameOrder>> result = PageObj.create(totalCount, request.getPageNum(), request.getPageSize(), list);
        List<TbGameOrder> gameOrders = result.getItems();
        List<RespOrderList> respOrderLists = Lists.newArrayList();
        for (TbGameOrder order : gameOrders) {
            RespOrderList orderList = new RespOrderList();
            BeanUtils.copyProperties(order, orderList);
            RespUserInfoBase user = baseService.queryUserMsg(order.getUid());
            if (user != null) {
                orderList.setUserName(user.getNickName());
            }
            respOrderLists.add(orderList);
        }
        page.setItems(respOrderLists);
        page.setPageCount(result.getPageCount());
        page.setPageNum(result.getPageNum());
        page.setSize(result.getSize());
        page.setTotal(result.getTotal());
        return APIResponse.returnSuccess(page);
    }

    @Override
    public APIResponse<RespOrderDetail> queryOrderDetail(TbGameOrder request) {
        RespOrderDetail respOrderDetail = new RespOrderDetail();
        TbGameOrderExample example = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = example.createCriteria();
        criteria.andTradeOrderNoEqualTo(request.getTradeOrderNo());
        List<TbGameOrder> orders = orderMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(orders)){
            return APIResponse.returnSuccess(respOrderDetail);
        }
        TbGameOrder order = orders.get(0);
        RespOrderList orderList = new RespOrderList();
        BeanUtils.copyProperties(order, orderList);


        RespUserInfoBase user = baseService.queryUserMsg(order.getUid());
        RespClubPlainInfo club = baseService.queryClubMsg(order.getClubid());
        if (user != null) {
            orderList.setUserName(user.getNickName());
        }
        if(club != null){
            orderList.setClubName(club.getClubName());
        }
        respOrderDetail.setOrder(orderList);
        Integer gameId = order.getGameEventId();
        TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(gameId);
        if(gameEvent == null){
            return APIResponse.returnSuccess(respOrderDetail);
        }
        RespActivity respActivity = new RespActivity();
        BeanUtils.copyProperties(gameEvent,respActivity);
        RespCity respCity = baseService.getRespCityById(gameEvent.getCityId());
        respActivity.setCityName(respCity.getName());
        RespClubPlainInfo clubDetail = baseService.queryClubMsg(respActivity.getClubId());
        if(clubDetail != null && respActivity != null){
            respActivity.setClubName(clubDetail.getClubName());
        }
        respOrderDetail.setEvent(respActivity);
        if(respActivity.getEndTime()!=null && respActivity.getEndTime().after(new Date())){
            respOrderDetail.getOrder().setIsFinish(1);
        }

        return APIResponse.returnSuccess(respOrderDetail);
    }

    @Override
    public APIResponse<TbGameEvent> queryGameEvent(TbGameEvent tbGameEvent) {
        TbGameEventExample example = new TbGameEventExample();
        TbGameEventExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(tbGameEvent.getId());
        return APIResponse.returnSuccess(gameEventMapper.selectByExample(example).get(0));
    }

    @Override
    public APIResponse authorizeClubPlaceList(ReqIdAndPage reqIdAndPage) {
        List<RespClubAuthorizeClubPlaceInfo> result = new ArrayList<>();
        TbGameClubOfficialExample example = new TbGameClubOfficialExample();
        TbGameClubOfficialExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(reqIdAndPage.getClubId());
        criteria.andSignExpireTimeGreaterThan(new Date());
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        int total = tbGameOfficialClubMapper.countByExample(example);
        if (total == 0) {
            return APIResponse.returnSuccess(PageObj.create(total, reqIdAndPage.getPageNo(), reqIdAndPage.getPageSize(), result));
        }
        example.setPage(new Page(reqIdAndPage.getPageNo() * reqIdAndPage.getPageSize(), reqIdAndPage.getPageSize()));
        example.setOrderByClause("id asc");
        List<TbGameClubOfficial> gameClubOfficials = tbGameOfficialClubMapper.selectByExample(example);
        if (null!=gameClubOfficials && gameClubOfficials.size()>0) {
            List<Integer> placeIds = new ArrayList<>();
            for (TbGameClubOfficial tbGameClubOfficial : gameClubOfficials) {
                placeIds.add(tbGameClubOfficial.getPlaceId());
            }
            Map<Integer, PlaceInfo> placeInfoMap = baseService.queryPlaceInfoMsgList(placeIds);
            for (TbGameClubOfficial tbGameClubOfficial : gameClubOfficials) {
                RespClubAuthorizeClubPlaceInfo clubPlaceInfo = new RespClubAuthorizeClubPlaceInfo();
                BeanUtils.copyProperties(tbGameClubOfficial, clubPlaceInfo);
                if (null!=placeInfoMap && placeInfoMap.size()>0) {
                    clubPlaceInfo.setPlaceInfo(placeInfoMap.get(tbGameClubOfficial.getPlaceId()));
                }
                result.add(clubPlaceInfo);
            }
        }
        return APIResponse.returnSuccess(PageObj.create(total, reqIdAndPage.getPageNo(), reqIdAndPage.getPageSize(), result));
    }

    @Override
    public APIResponse<List<TbGameBanner>> getBannerList(ReqId reqId) {
        TbGameBannerExample example = new TbGameBannerExample();
        TbGameBannerExample.Criteria criteria = example.createCriteria();
        if (null == reqId || null == reqId.getCityId()){
         return APIResponse.returnFail("cityId不能为空！");
        }
        example.setOrderByClause(" priority ");
        criteria.andCityIdEqualTo(reqId.getCityId());
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        List<TbGameBanner> gameBannerList = tbGameBannerMapper.selectByExample(example);
        return APIResponse.returnSuccess(gameBannerList);
    }

    @Override
    public APIResponse addBannerList(ReqBannerList bannerList) {
        if ( null == bannerList || null == bannerList.getBannerList() || bannerList.getBannerList().size() == 0){
            return APIResponse.returnFail("传入数据为空！");
        }
        Integer count = this.getBannerCount(bannerList.getBannerList().get(0).getCityId()).getData();
        if (count >= GameConstants.BANNER_NUM){
            return APIResponse.returnFail("该城市下的banner图数量已经达到最大数量 —— "+GameConstants.BANNER_NUM+"，请联系管理员更改默认值" );
        }
        Integer size = bannerList.getBannerList().size();
        if((size + count) > GameConstants.BANNER_NUM){
            return APIResponse.returnFail("该城市下的banner图数量为"+count+"，将要添加"+size+"条记录，已经超过"+GameConstants.BANNER_NUM+"条,请联系管理员更改默认值" );
        }

        TbGameBanner tbGameBanner = new TbGameBanner();
        int i = 0;
        for (ReqBanner banner : bannerList.getBannerList()){
            BeanUtils.copyProperties(banner,tbGameBanner);
            tbGameBanner.setIsDelete(GameConstants.IS_NOT_DELETE);
            tbGameBannerMapper.insertSelective(tbGameBanner);
            i++;
        }
        return APIResponse.returnSuccess("插入了"+i+"条数据");
    }

    @Override
    public APIResponse<Integer> getBannerCount(Integer cityId) {
        if (null == cityId){
            return APIResponse.returnFail("城市Id不能为空");
        }
        TbGameBannerExample example = new TbGameBannerExample();
        TbGameBannerExample.Criteria criteria = example.createCriteria();
        criteria.andCityIdEqualTo(cityId);
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        Integer count = tbGameBannerMapper.countByExample(example);
        return APIResponse.returnSuccess(count);
    }

    @Override
    public APIResponse editBanner(ReqBanner banner) {
        if (null == banner){
            return APIResponse.returnFail("传入对象不能为空！");
        }
        if(null == banner.getId()){
            return APIResponse.returnFail("传入banner的ID不能为空！");
        }
        TbGameBanner tbGameBanner = tbGameBannerMapper.selectByPrimaryKey(banner.getId());
        if (null == tbGameBanner){
            return APIResponse.returnFail("请检查传入的banner图Id，数据库不存在该记录！");
        }
        BeanUtils.copyProperties(banner, tbGameBanner);
        tbGameBannerMapper.updateByPrimaryKey(tbGameBanner);
        return APIResponse.returnSuccess("记录 "+ banner.getId() + " 更新成功");
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor={Exception.class})
    public APIResponse setBannerPriority(ReqBannerPriorityList priorityList) {
        if (null == priorityList || null == priorityList.getReqBannerPriorityList() || priorityList.getReqBannerPriorityList().size() == 0){
            return APIResponse.returnFail("传入对象不能为空！");
        }
        for (ReqBannerPriority priority :priorityList.getReqBannerPriorityList()){
            TbGameBanner tbGameBanner = tbGameBannerMapper.selectByPrimaryKey(priority.getId());
            tbGameBanner.setPriority(priority.getPriority());
            tbGameBannerMapper.updateByPrimaryKey(tbGameBanner);
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse deleteBanner(Integer id) {
        TbGameBanner tbGameBanner = new TbGameBanner();
        tbGameBanner.setIsDelete(GameConstants.IS_DELETE);
        TbGameBannerExample example = new TbGameBannerExample();
        TbGameBannerExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        Integer result = tbGameBannerMapper.updateByExampleSelective(tbGameBanner,example);
        return APIResponse.returnSuccess(result);
    }


    private boolean validateGameEventExist(Integer placeId, Integer gameMonth, Integer categoryId){
        TbGameEventExample example = new TbGameEventExample();
        TbGameEventExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andCategoryIdEqualTo(categoryId);
        criteria.andGameMonthEqualTo(gameMonth);
        List<TbGameEvent> tbGameEvents = tbGameEventMapper.selectByExample(example);
        if (null!=tbGameEvents && tbGameEvents.size()>0) {
            return true;
        }
        return false;
    }

    @Override
    public APIResponse refound(ReqFoundOrder request) {
        TbGameOrderExample orderExample = new TbGameOrderExample();
        TbGameOrderExample.Criteria orderCriteria = orderExample.createCriteria();
        orderCriteria.andTradeOrderNoEqualTo(request.getOrderNo());
        List<TbGameOrder> orders = orderMapper.selectByExample(orderExample);
        if(CollectionUtils.isEmpty(orders)){
            return APIResponse.returnFail("退款失败！");
        }
        TbGameOrder order = orders.get(0);
        TbGameEvent gameEvent = gameEventMapper.selectByPrimaryKey(order.getGameEventId());
        return gameSignUpService.refoundUserPay(order, gameEvent);
    }

    @Override
    public PageObj<List<TbGameCommonParameter>> getCommonParameterList(ReqParamer reqParamer) {
        List<TbGameCommonParameter> parameterList = new ArrayList<>();
        TbGameCommonParameterExample example = new TbGameCommonParameterExample();
        TbGameCommonParameterExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        if(null != reqParamer.getParameter() && reqParamer.getParameter().length() > 0){
            criteria.andParameterGroupLike(reqParamer.getParameter());
        }
        int total = tbGameCommonParameterMapper.countByExample(example);
        if(total == 0){
            return PageObj.create(total,reqParamer.getPageNo(),reqParamer.getPageSize(),parameterList);
        }
        example.setPage(new Page(reqParamer.getPageNo()*reqParamer.getPageSize(),reqParamer.getPageSize()));
        example.setOrderByClause(" id desc");
        parameterList =  tbGameCommonParameterMapper.selectByExample(example);
        return PageObj.create(total, reqParamer.getPageNo(), reqParamer.getPageSize(), parameterList);
    }

    @Override
    public APIResponse addCommonParameter(TbGameCommonParameter commonParameter) {
        TbGameCommonParameter parameter = new TbGameCommonParameter();
        /**
         * 判断 parameterKey 是否重复
         */
        TbGameCommonParameterExample example = new TbGameCommonParameterExample();
        TbGameCommonParameterExample.Criteria criteria = example.createCriteria();
        if(null != commonParameter.getParameterKey()){
            criteria.andParameterKeyEqualTo(commonParameter.getParameterKey());
        }
        List<TbGameCommonParameter> gameCommonParameterList = tbGameCommonParameterMapper.selectByExample(example);
        if(null != gameCommonParameterList && gameCommonParameterList.size() > 0){
            return  APIResponse.returnFail(" 数据库已经存在Key值为" + commonParameter.getParameterKey()+"，请重新输入！");
        }
        BeanUtils.copyProperties(commonParameter,parameter);
        parameter.setIsEnable(GameConstants.IS_ENABLE);
        parameter.setIsDelete(GameConstants.IS_NOT_DELETE);
        parameter.setCreateTime(new Date());
        parameter.setUpdateTime(new Date());
        tbGameCommonParameterMapper.insert(parameter);
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse editCommonParameter(TbGameCommonParameter commonParameter) {
        TbGameCommonParameter parameter = new TbGameCommonParameter();
        BeanUtils.copyProperties(commonParameter, parameter);
        tbGameCommonParameterMapper.updateByPrimaryKeySelective(parameter);
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse changeCommonParameter(Integer id,Byte status) {
        TbGameCommonParameter tbGameCommonParameter = new TbGameCommonParameter();
        tbGameCommonParameter.setId(id);
        tbGameCommonParameter.setIsEnable(status);
        tbGameCommonParameterMapper.updateByPrimaryKeySelective(tbGameCommonParameter);
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse authorizeClubList() {
        TbGameClubOfficialExample example = new TbGameClubOfficialExample();
        TbGameClubOfficialExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(GameConstants.IS_NOT_DELETE);
        example.setPage(new Page(0, 30));
        List<TbGameClubOfficial>  temp = tbGameOfficialClubMapper.selectByExample(example);
        Map<Integer, RespClubPlainInfo> map = null;
        if (CollectionUtils.isNotEmpty(temp)) {
            List<Integer> clubIds = new ArrayList<>();
            for (TbGameClubOfficial t : temp) {
                clubIds.add(t.getClubId());
            }
            map = baseService.queryClubMsg(clubIds);
        }
        return  APIResponse.returnSuccess(map);
    }

}
